package net.sk.gti;

import java.util.HashMap;

import net.bat.util.Cfg;
import net.sk.pt.State;
import net.sk.web.Keeper;
import net.sk.web.Provider;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;

public class gtiIoHandler extends IoHandlerAdapter {
	public static String PR_GTI_AP="PR_GTI_AP_";
	Provider pr=null;	
	public gtiIoHandler(){
	}
	public Provider getPR(){
		if(pr!=null){
			return pr;
		}
		//ap主动报,多个AP接入时无法解决来自哪个AP
        pr = new Provider(new Keeper(),PR_GTI_AP);
        Cfg.getSC().addProvider(pr);		
		return pr;
	}
    public void sessionOpened(IoSession session) throws Exception {
    }

    /**
     * This method will be called whenever an exception occurs.  For this handler,
     * the logger will generate a warning message.
     * 
     * @see org.apache.mina.core.service.IoHandlerAdapter#exceptionCaught(org.apache.mina.core.session.IoSession, java.lang.Throwable)
     */
    public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
    }

    /**
     * Handle incoming messages.
     * 
     * @see org.apache.mina.core.service.IoHandlerAdapter#messageReceived(org.apache.mina.core.session.IoSession, java.lang.Object)
     */
    public void messageReceived(IoSession session, Object message) throws Exception {
    	gtiData[] gds = (gtiData[]) message;
    	for(int i=0; i<gds.length; i++){
    		State s = gd2State(gds[i]);
    		getPR().send(s);
    		System.out.println(s);
    	}
    }

    public static State gd2State(gtiData gd){
    	State s = new State();
    	s.setCn("GTI.Node");
    	s.setAction(State.ACTION_PUT);
    	s.setKey(gd.node_id);
    	HashMap<String,Object> its = new HashMap<String,Object>();
    	its.put("rssi", gd.rssi);
    	its.put("tempr1", gd.tempr1);
    	its.put("tempr2", gd.tempr2);
    	its.put("humi", gd.humi);
    	its.put("tm", gd.tm);
    	s.setItems(its);
    	return s;
    }
}
